<template>
  <el-scrollbar ref="scrollbarRef">
    <el-collapse v-model="activeNames">
      <el-collapse-item v-for="(form, index) in opsList" :key="form.id" :name="form.id">
        <template #title>
          第{{ index + 1 }}次延期
        </template>
        <el-form :model="form" label-width="150px" :inline="true">
          <el-card bordered shadow="hover" class="card">
            <el-form-item label="区县">
              <el-input v-model="form.county" :disabled="!form.editing" style="width: 250px" />
            </el-form-item>
            <el-form-item label="方案类型">
              <el-input v-model="form.planType" :disabled="!form.editing" style="width: 250px" />
            </el-form-item>
            <el-form-item label="小区名称">
              <el-input v-model="form.cellName" :disabled="!form.editing" style="width: 680px" />
            </el-form-item>
            <el-form-item label="解决情况">
              <!-- <el-input v-model="form.resolutionStatus" :disabled="!form.editing" style="width: 680px" /> -->
              <el-select v-model="form.resolutionStatus" :disabled="!form.editing" placeholder=" 请选择" clearable
                style="width: 680px">
                <el-option label="已解决" value="已解决"></el-option>
                <el-option label="延期解决" value="延期解决"></el-option>
                <el-option label="无法解决" value="无法解决"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="满意情况">
              <el-select v-model="form.satisfactionSituation" :disabled="!form.editing" placeholder="请选择" clearable
                style="width: 680px">
                <el-option label="满意" value="满意"></el-option>
                <el-option label="不满意" value="不满意"></el-option>
                <el-option label="不确定" value="不确定"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="原因分类">
              <el-select v-model="form.closureOpinion" :disabled="!form.editing" placeholder="请选择原因分类" clearable
                style="width: 680px">
                <!-- <el-option v-for="dict in nhp_closure_opinion" :key="dict.value" :label="dict.label"
                  :value="dict.value" /> -->
                <el-option v-for="dict in getClosureOpinion()" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="解决措施">
              <el-select v-model="form.solution" :disabled="!form.editing" placeholder="请选择解决措施" clearable
                style="width: 680px" @change="selectSolution">
                <el-option v-for="dict in getSolutionOpinion(delaySolutionMappingOne)" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="处理过程">
              <el-input type="textarea" rows="3" :disabled="!form.editing" v-model="form.handleProcess"
                style="width: 740px" />
            </el-form-item>
            <!-- <el-form-item label="延期时间">
              <el-input-number v-model="form.delayTime" :disabled="!form.editing" style="width: 250px" :precision="1"
                :step="0.1" />
            </el-form-item> -->
            <el-form-item label="延期时间">
              <el-date-picker v-model="form.delayTime" type="datetime"
                :disabled="detailFrom.expertGroupProcessingResult === '延期解决'" placeholder="请选择日期"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="优化单号">
              <el-input v-model="form.optimizeOrderId" :disabled="!form.editing" style="width: 250px" />
            </el-form-item>
            <el-form-item label="方案是否完成">
              <el-select v-model="form.planCompletedStatus" :disabled="!form.editing" placeholder="请选择方案是否完成" clearable
                style="width: 250px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否需要再次方案">
              <el-select v-model="form.needPlanAgain" :disabled="!form.editing" placeholder="请选择是否需要再次方案" clearable
                style="width: 250px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否有再次方案">
              <el-select v-model="form.havePlanAgain" :disabled="!form.editing" placeholder="请选择是否有再次方案" clearable
                style="width: 250px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否完成">
              <el-select v-model="form.completedStatus" :disabled="!form.editing" placeholder="请选择是否完成" clearable
                style="width: 250px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="延期原因" v-if="index > 0">
              <el-input v-model="form.delayReason" disabled style="width: 680px" />
            </el-form-item>
            <el-form-item class="button-group">
              <el-row>
                <el-col :span="24" style="text-align: right;" v-if="opsList.length === 1">
                  <el-button type="success" @click="updateForm(form)">保存</el-button>
                  <!-- <el-button @click="cancelUpdate()">取消</el-button> -->
                </el-col>
              </el-row>
            </el-form-item>
          </el-card>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <el-form v-for="form in forms" :rules="form.rules" :key="form.id" :model="form.data" label-width="150px"
      :inline="true">
      <el-card bordered shadow="hover" class="card">
        <template #header>
          <div class="card-header">
            <span>第{{ opsList.length + 1 }}次延期</span>
          </div>
        </template>
        <el-form-item label="区县">
          <el-input v-model="form.data.county" style="width: 250px" />
        </el-form-item>
        <el-form-item label="方案类型">
          <el-input v-model="form.data.planType" style="width: 250px" />
        </el-form-item>
        <el-form-item label="小区名称">
          <el-input v-model="form.data.cellName" style="width: 680px" />
        </el-form-item>
        <el-form-item label="解决情况">
          <!-- <el-input v-model="form.data.resolutionStatus" style="width: 680px" /> -->
          <el-select v-model="form.data.resolutionStatus" placeholder="请选择" clearable style="width: 680px">
            <el-option label="已解决" value="已解决"></el-option>
            <el-option label="延期解决" value="延期解决"></el-option>
            <el-option label="无法解决" value="无法解决"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="满意情况">
          <el-select v-model="form.data.satisfactionSituation" placeholder="请选择" clearable style="width: 680px">
            <el-option label="满意" value="满意"></el-option>
            <el-option label="不满意" value="不满意"></el-option>
            <el-option label="不确定" value="不确定"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原因分类">
          <el-select v-model="form.data.closureOpinion" placeholder="请选择原因分类" clearable style="width: 680px">
            <!-- <el-option v-for="dict in nhp_closure_opinion" :key="dict.value" :label="dict.label" :value="dict.value" /> -->
            <el-option v-for="dict in getClosureOpinion()" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="解决措施">
          <el-input v-model="form.data.solution" style="width: 680px" />
        </el-form-item> -->
        <el-form-item label="解决措施">
          <el-select v-model="form.data.solution" placeholder="请选择解决措施" clearable style="width: 680px"
            @change="selectSolution">
            <el-option v-for="dict in getSolutionOpinion(delaySolutionMappingNotOne)" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理过程">
          <el-input type="textarea" rows="3" v-model="form.data.handleProcess" style="width: 740px" />
        </el-form-item>
        <!--  <el-form-item label="延期时间">
          <el-input-number v-model="form.data.delayTime" style="width: 250px" :precision="1" :step="0.1" />
        </el-form-item> -->
        <el-form-item label="延期时间">
          <el-date-picker v-model="form.data.delayTime" :disabled="detailFrom.expertGroupProcessingResult === '延期解决'"
            type="datetime" placeholder="请选择日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="优化单号">
          <el-input v-model="form.data.optimizeOrderId" style="width: 250px" />
        </el-form-item>
        <el-form-item label="方案是否完成">
          <el-select v-model="form.data.planCompletedStatus" placeholder="请选择方案是否完成" clearable style="width: 250px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要再次方案">
          <el-select v-model="form.data.needPlanAgain" placeholder="请选择是否需要再次方案" clearable style="width: 250px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有再次方案">
          <el-select v-model="form.data.havePlanAgain" placeholder="请选择是否有再次方案" clearable style="width: 250px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否完成">
          <el-select v-model="form.data.completedStatus" placeholder="请选择是否完成" clearable style="width: 250px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="延期原因" prop="delayReason">
          <el-input v-model="form.data.delayReason" type="textarea" rows="3" style="width: 680px" />
        </el-form-item>
        <el-form-item class="button-group">
          <el-row>
            <el-col :span="24" style="text-align: right;">
              <el-button type="success" @click="saveForm(form)">保存</el-button>
              <el-button @click="cancelForm(form)">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-card>
    </el-form>
    <div class="button-container">
      <el-button type="primary" round @click="addForm">新增延期操作</el-button>
    </div>
  </el-scrollbar>
</template>

<script setup>
import { ref, toRefs, toRef, reactive, computed, defineProps, nextTick } from 'vue'
import * as complainApi from "@/api/complain/complain";
const { proxy } = getCurrentInstance();
const { nhp_network_type, nhp_county_type_short, nhp_closure_opinion } = proxy.useDict("nhp_network_type", "nhp_county_type_short", "nhp_closure_opinion");

import { delayOpinionMapping, mapInput, getClosureOpinion, getSolutionOpinion, delaySolutionMappingOne, delaySolutionMappingNotOne } from './mappingUtils.js';

const emit = defineEmits(["closeDialog", "saveSuccess"]);

const props = defineProps({
  detailFrom: {
    type: Object,
    default: () => { },
  }
})

const scrollbarRef = ref(null);

const activeNames = ref([]);
const opsList = ref([])
const forms = ref([]);
const options = [
  {
    key: "是",
    value: "是"
  },
  {
    key: "否",
    value: "否"
  },
]

const getDelayTime = (input, mapping) => {
  let delayDay = mapInput(input, mapping)?.delayTime.replace(/天/, '')
  // 从预期解决时间[expectedResolveTime]中获取开始日期
  let expectedTime = props.detailFrom.expectedResolveTime
  // console.log("expectedTime", expectedTime, delayDay)
  let delayTime = expectedTime ? new Date(expectedTime).getTime() + delayDay * 24 * 60 * 60 * 1000 : null

  return formatDate(delayTime)
}

const selectSolution = (val) => {
  // 表示更新
  if ((opsList.value.length === 0 || opsList.value.length === 1) && forms.value.length !== 1) {
    let delayTime = getDelayTime(val, delaySolutionMappingOne)
    opsList.value[0].delayTime = delayTime

    return
  }

  // 表示新增
  let delayTime = getDelayTime(val, delaySolutionMappingNotOne)
  forms.value[0].data.delayTime = delayTime
}

const initDelayDetail = () => {
  let newFormData = getNewFormData()
  console.log("newFormData", newFormData)

  // 初始化延期操作数据
  forms.value = [];

  // 查询延期操作列表 - 如果有数据,回显
  queryComplaintList(() => {
    // console.log("查询延期操作列表,opsList被赋值", opsList.value);

    // 如果没有回显数据,新增一个
    if (opsList.value.length == 0) {
      saveApi(complainApi.addComplaintDelayOperation, newFormData.data, res => {
        // 防止重复点击
        if (opsList.value.length == 0) {
          // newFormData.editing = true;
          emit("saveSuccess");

          // 重新查询延期操作列表-回显
          queryComplaintList()
        }
      })
    }
  })
}

function queryComplaintList(next) {
  let param = {
    orderId: props.detailFrom.orderId,
  };
  complainApi.queryComplaintListbyOrderId(param).then((res) => {
    if (res.code == 200) {
      opsList.value = res.data;
      if (opsList.value.length === 1) {
        opsList.value[0].editing = true;
      } else {
        opsList.value.forEach((item, index) => {
          item.editing = false;
        })
      }
      activeNames.value = opsList.value.map(form => form.id);

      if (next) next()
    } else {
      proxy.$message.error(res.msg);
    }
  });
}

const formatDate = (cellValue) => {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

const getNewFormData = (isAdd = false) => {
  // 如果是新增,默认没有数据
  if (isAdd) {
    return {
      data: {
        orderId: props.detailFrom.orderId,  // 工单
        eomsId: props.detailFrom.eomsId,  // eoms工单
        county: props.detailFrom.county,  // 区县
      },
      editing: true,
    }
  }

  /**
   * 小区名称和方案类型从专家组处理-方案实施情况（当前处理进展）字段中获取: [expertGroupImplementationStatus]
   * 小区名称匹配 /涉及站点：(.*)/
   * 方案类型匹配 /涉及方案：(.*)/
   */
  // 专家组处理-方案实施情况（当前处理进展）字段
  let expertGroupImplementationStatus = props.detailFrom.expertGroupImplementationStatus
  // 匹配小区名称
  let addressMatch = expertGroupImplementationStatus.match(/涉及站点：(.*)/)
  let address = addressMatch ? addressMatch[1] : null

  // 匹配涉及方案
  let planTypeMatch = expertGroupImplementationStatus.match(/涉及方案：(.*)/)
  let planType = planTypeMatch ? planTypeMatch[1] : null

  /**
   * 报结意见改成原因分类(字段名称不变[closureOpinion])
   * 原因分类从专家组处理-问题原因分类[expertGroupReasonCategory]中获取: [expertGroupReasonCategory]
   */
  let closureOpinionResult = mapInput(props.detailFrom.expertGroupReasonCategory, delayOpinionMapping)
  // console.log("closureOpinionResult", props.detailFrom.expertGroupReasonCategory, closureOpinionResult)

  // 从专家组处理-解决措施分类[expertGroupSolutionCategory]来获取解决措施
  let solution = props.detailFrom.expertGroupSolutionCategory

  // 处理过程
  let handleProcess = props.detailFrom.expertGroupImplementationStatus

  /**
   * 延期时间
   * 需要判断 专家组处理-解决措施分类[expertGroupSolutionCategory] 的显示,并作映射,返回天
   * 从预期解决时间[expectedResolveTime]中获取开始日期
   */
  let delayTime = getDelayTime(solution, delaySolutionMappingOne)

  return {
    data: {
      orderId: props.detailFrom.orderId,  // 工单
      eomsId: props.detailFrom.eomsId,  // eoms工单
      county: props.detailFrom.county,  // 区县
      planType,  // 替换成方案类型(从涉及方案中同步): 专家组处理-方案实施情况（当前处理进展）字段中获取: [expertGroupImplementationStatus]
      cellName: address,  // 小区名称从GroupImplementationStatus中提取
      resolutionStatus: props.detailFrom.expertGroupProcessingResult,  // 解决情况
      closureOpinion: closureOpinionResult?.closureOpinion,  // 原因分类
      solution,  // 从专家组处理-解决措施分类[expertGroupSolutionCategory]来获取解决措施
      handleProcess,  // 处理过程
      delayTime  // 延期时间
    },
    editing: true,
  };
}

function addForm() {
  if (forms.value.length > 0) {
    return;
  }
  // console.log(forms.value)
  forms.value.push({
    ...getNewFormData(true),
    rules: {
      delayReason: [
        { required: true, message: '请输入延期原因', trigger: 'blur' }
      ]
    }
  });
  opsList.value[0].editing = false;
  scrollToBottom();
}

function scrollToBottom() {
  if (scrollbarRef.value) {
    // 获取 el-scrollbar 内部实际可滚动的 DOM 元素
    const scrollbarEl = scrollbarRef.value.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbarEl) {
      // 设置 scrollTop 为 scrollHeight 实现滚动到最底部
      scrollbarEl.scrollTop = scrollbarEl.scrollHeight;
    }
  }
}

const saveApi = (api, params, next) => {
  api(params).then((res) => {
    if (res.code == 200) {
      next(res)
    } else {
      proxy.$message.error(res.msg);
    }
  })
}

function saveForm(form) {
  saveApi(complainApi.addComplaintDelayOperation, form.data, res => {
    proxy.$message({
      message: "保存成功",
      type: "success",
    });
    form.editing = false;
    forms.value = [];
    queryComplaintList();
    emit("closeDialog")
    emit("saveSuccess");
  })
}

const updateForm = (form) => {
  complainApi.updateComplaintDelayOperation(form).then((res) => {
    if (res.code == 200) {
      // console.log("updateForm", res)

      proxy.$message({
        message: "更新成功",
        type: "success",
      });

      opsList.value[0].editing = false;
      emit("closeDialog")
      emit("saveSuccess");
    } else {
      proxy.$message.error(res.msg);
    }
  });
}

function cancelForm(form) {
  forms.value = [];
}

const cancelUpdate = () => {
  opsList.value[0].editing = true;
}

defineExpose({
  initDelayDetail
})
</script>

<style lang="scss" scoped></style>